//
//  AppGlobalManager.m
//  Chehu_User
//
//  Created by Luke on 15/10/13.
//  Copyright (c) 2015年 Chehu. All rights reserved.
//

#import "TYGlobalManager.h"
#import "TYUserInfoModel.h"
#import "TYTempInfoModel.h"


@implementation TYGlobalManager

//警告:这个宏实现了NSCoding协议,不能删除
MJExtensionCodingImplementation


#pragma mark - 初始化 AppGlobalManager 单例

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static TYGlobalManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

+ (instancetype)shareInstance
{
    return [[self alloc] init];
}


/**
 *  所有临时信息Model数组
 */
- (NSMutableArray *)tempInfoModelArr
{
    if (!_tempInfoModelArr) {
        _tempInfoModelArr = [NSMutableArray array];
    }
    return _tempInfoModelArr;
}

#pragma mark -================ 单例对象操作 ================

/**
 *  保存单例到数据库
 */
+ (void)saveGlobalManagerToFMDB
{
    NSString *userID = GetUserDefault(UserIDUserDefaultsKey);
    if (userID) {
        TYGlobalManager *appGlobalManager = [TYGlobalManager shareInstance];
        [TYFMDBTool saveDataToDB:appGlobalManager byObjectId:userID toTable:AppGlobalInfoTableType];
    }
}


/**
 *  注销登录处理
 */
+ (void)logoutDealWithFMDB
{
    TYGlobalManager *appGlobalManager = [TYGlobalManager shareInstance];
    appGlobalManager.isLogin = NO;
    appGlobalManager.currentShopInfo = nil;
    
    [TYGlobalManager saveGlobalManagerToFMDB];
}

/**
 *  启动程序时从数据库初始化用户信息单例对象
 */
+ (TYGlobalManager *)getAppGlobalManagerFromDB
{
    NSString *userID = GetUserDefault(UserIDUserDefaultsKey);
    if (userID) {
        TYGlobalManager *appGlobalManager = [TYFMDBTool getObjectById:userID fromTable:AppGlobalInfoTableType];
        NSLog(@"启动程序时从数据库获取所有用户信息:%@",appGlobalManager);
        return appGlobalManager;
    }
    return nil;
}



@end
